/* eslint-disable */
import { MinusCircledIcon } from '@radix-ui/react-icons'
import * as React from 'react'
import { SearchIcon } from '../../bs-icons/search'
import { cname, generateUUID } from '../utils'
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}

const Input = React.forwardRef<HTMLInputElement, InputProps>(({ className, type, ...props }, ref) => {
  return (
    <input
      type={type}
      className={cname(
        'flex h-9 w-full rounded-md border border-input bg-[#FAFBFC] px-3 py-1 text-sm text-[#111] shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
        className
      )}
      ref={ref}
      {...props}
    />
  )
})
Input.displayName = 'Input'

const SearchInput = React.forwardRef<
  HTMLInputElement,
  InputProps & { inputClassName?: string; iconClassName?: string }
>(({ className, inputClassName, iconClassName, ...props }, ref) => {
  return (
    <div className={cname('relative', className)}>
      <SearchIcon className={cname('absolute left-2 top-2 h-5 w-5', iconClassName)} />
      <Input type="text" ref={ref} className={cname('bg-search-input pl-8', inputClassName)} {...props}></Input>
    </div>
  )
})

SearchInput.displayName = 'SearchInput'

/**
 * 多行文本
 */
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}

const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(({ className, ...props }, ref) => {
  return (
    <textarea
      className={cname(
        'flex min-h-[80px] w-full rounded-md border border-input bg-[#FAFBFC] px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
        className
      )}
      ref={ref}
      {...props}
    />
  )
})
Textarea.displayName = 'Textarea'

/**
 * input list
 */
const InputList = React.forwardRef<
  HTMLDivElement,
  InputProps & {
    rules: any[]
    value?: string[]
    inputClassName?: string
    defaultValue?: string[]
    onChange?: (values: string[]) => void
  }
>(({ rules, className, inputClassName, value = [], defaultValue = [], ...props }, ref) => {
  // 初始化 inputs 状态，为每个值分配唯一 ID
  const [inputs, setInputs] = React.useState(() => value.map(val => ({ id: generateUUID(8), value: val })))

  React.useEffect(() => {
    // 仅为新增的值分配新的 ID
    const updatedInputs = value.map((val, index) => {
      return inputs[index] && inputs[index].value === val
        ? inputs[index] // 如果当前输入项与外部值相同，则保持不变
        : { id: generateUUID(8), value: val } // 否则，创建新的输入项
    })
    setInputs(updatedInputs)
  }, [value]) // 依赖项中包含 value，确保外部 value 更新时同步更新

  const handleChange = (newValue, id, index) => {
    let newInputs = inputs.map(input => (input.id === id ? { ...input, value: newValue } : input))
    // push
    // if (index === newInputs.length - 1 && newInputs.length < 10) {
    if (index === newInputs.length - 1) {
      newInputs = [...newInputs, { id: generateUUID(8), value: '' }]
    }
    setInputs(newInputs)
    props.onChange(newInputs.map(input => input.value))
  }

  // delete input
  const handleRemoveInput = id => {
    const newInputs = inputs.filter(input => input.id !== id)
    setInputs(newInputs)
    props.onChange(newInputs.map(input => input.value))
  }

  return (
    <div className={cname('', className)}>
      {inputs.map((item, index) => (
        <div className="relative mt-2" key={item.id}>
          <Input
            key={item.id}
            defaultValue={item.value}
            className={cname('pr-8', inputClassName)}
            placeholder={props.placeholder || ''}
            onChange={e => handleChange(e.target.value, item.id, index)}
            onInput={(e: any) => {
              rules.some(rule => {
                if (rule.maxLength && e.target.value.length > rule.maxLength) {
                  e.target.nextSibling.textContent = rule.message
                  e.target.nextSibling.style.display = ''
                  return true
                }
                e.target.nextSibling.style.display = 'none'
              })
            }}
            // onFocus={(e) => {
            //     if (e.target.value && index === inputs.length - 1) {
            //         setInputs([...inputs, { id: generateUUID(8), value: '' }]);
            //     }
            // }}
          ></Input>
          <p className="text-sm text-red-500" style={{ display: 'none' }}></p>
          {index !== inputs.length - 1 && (
            <MinusCircledIcon
              onClick={(e: any) => {
                e.target.previousSibling.style.display = 'none'
                handleRemoveInput(item.id)
              }}
              className="absolute right-2 top-2.5 cursor-pointer text-gray-500 hover:text-gray-700"
            />
          )}
        </div>
      ))}
    </div>
  )
})

export { Input, InputList, SearchInput, Textarea }
